<template>
  <div class="container">
    <div
      class="ball"
      ref="ball"
    >
      <el-icon>
        <ForkSpoon />
      </el-icon>
    </div>
    <input
      type="file"
      @change="fileChanged"
      accept="image/*"
      style="display: none"
      id="fileInput"
    >
    </input>
    <el-row>
      <el-col
        :xs="24"
        :sm="12"
        :md="12"
        :lg="16"
      >
        <!-- <el-select
          v-model="YY_TIME"
          size="large"
          placeholder="请选择取餐时间"
          clearable
        >
          <el-option
            v-for="option in YY_TIME_Options"
            :key="option.value"
            :value="option.value"
            :label="option.label"
          >
          </el-option>
        </el-select> -->
        <h1>取货时间</h1>
        <h1 v-if="YY_TIME_Options.length > 0"> {{YY_TIME_Options[0].value.split(' ')[0] }}</h1>
        <h1 v-if="YY_TIME_Options.length > 0"> {{YY_TIME_Options[0].value.split(' ')[1] }}</h1>
      </el-col>
    </el-row>

    <!-- 菜单列表 -->
    <el-row :gutter="20">
      <el-col
        :xs="24"
        :sm="12"
        :md="12"
        :lg="16"
      >
        <el-row :gutter="10">
          <el-col
            v-for="item in menu"
            :key="item.CD_ID"
            :xs="12"
            :sm="12"
            :md="12"
            :lg="8"
          >
            <el-card class="menu-item">
              <img
                :src="item.URL"
                :alt="item.NAME"
                class="item-image"
              />
              <div class="item-info">
                <h3>{{ item.NAME }}</h3>
                <el-collapse-transition>
                  <p class="DESCRIPTION">
                    {{ item.DESCRIPTION || '&nbsp;' }}
                  </p>
                </el-collapse-transition>
                <div class="item-footer">
                  <span class="PRICE">¥{{ item.PRICE }}</span>
                  <el-button
                    style="color:rgb(0, 53, 140)"
                    @click="addToCart($event, item)"
                  >
                    ＋加入
                  </el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-col>

      <!-- 桌面端购物车 -->
      <el-col
        :xs="0"
        :sm="12"
        :md="12"
        :lg="8"
      >
        <el-card class="cart-desktop">
          <h2 id="pcShop">购物车 ({{ cartTotalQuantity }})</h2>
          <div
            v-if="cartItems.length === 0"
            class="empty-cart"
          >
            <el-empty DESCRIPTION="购物车为空" />
          </div>
          <div v-else>
            <div
              v-for="(item, index) in cartItems"
              :key="item.CD_ID"
              class="cart-item"
            >
              <div class="item-info">
                <h3>{{ item.NAME }}</h3>
                <div class="quantity-control">
                  <el-button
                    circle
                    @click="decreaseQuantity(index)"
                    :disabled="item.quantity <= 1"
                  >
                    -
                  </el-button>
                  <span class="quantity">{{ item.quantity }}</span>
                  <el-button
                    circle
                    @click="increaseQuantity(index)"
                  >
                    +
                  </el-button>
                </div>
              </div>
              <div class="item-actions">
                <span class="PRICE">¥{{ (item.PRICE * item.quantity).toFixed(2) }}</span>
                <el-button
                  type="danger"
                  circle
                  @click="removeItem(index)"
                >🗑</el-button>
              </div>
            </div>
            <el-divider />
            <div class="total-PRICE">
              <h3>总计：¥{{ cartTotalPrice.toFixed(2) }}</h3>
              <!-- <el-button
                type="primary"
                @click="drawerVisible = true"
              >去支付</el-button> -->

              <el-button
                style="margin-top:10px"
                type="success"
                size="large"
                @click="submitOrder"
              >提交订单</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 移动端购物车 -->
    <el-affix
      :offset="20"
      class="mobile-cart"
      id="mobileShop"
    >
      <el-badge
        :value="cartTotalQuantity"
        :max="99"
      >
        <el-button
          type="primary"
          circle
          size="large"
          @click="drawerVisible = true"
        >🛒</el-button>
      </el-badge>
    </el-affix>

    <el-drawer
      v-model="drawerVisible"
      title="购物车"
      size="90%"
      direction="btt"
      class="mobile-drawer"
    >
      <div
        v-if="cartItems.length === 0"
        class="empty-cart"
      >
        <el-empty DESCRIPTION="购物车为空" />
      </div>
      <div v-else>
        <div
          v-for="(item, index) in cartItems"
          :key="item.CD_ID"
          class="cart-item"
        >
          <div class="item-info">
            <span>{{ item.NAME }}</span>
            <div class="quantity-control">
              <el-button
                circle
                @click="decreaseQuantity(index)"
                :disabled="item.quantity <= 1"
              >
                -
              </el-button>
              <span class="quantity">{{ item.quantity }}</span>
              <el-button
                circle
                @click="increaseQuantity(index)"
              >
                +
              </el-button>
            </div>
          </div>
          <div class="item-actions">
            <span class="PRICE">¥{{ (item.PRICE * item.quantity).toFixed(2) }}</span>
            <el-button
              type="danger"
              circle
              @click="removeItem(index)"
            >🗑</el-button>
          </div>
        </div>
        <el-divider />
        <div class="total-PRICE">
          <el-row>
            <el-col :span="24">
              <span>取货时间: {{ YY_TIME_Options[0].value }}</span>
            </el-col>
          </el-row>

          <el-row style="margin-top: 10px;">
            <el-col :span="10">
              <span>备注:</span>
            </el-col>
            <el-col :span="14">
              <el-input
                v-model="REMARK"
                maxlength="50"
              />
            </el-col>
          </el-row>
          <!-- <span style="font-weight:bold">总计：¥{{ cartTotalPrice.toFixed(2) }}</span> -->
          <!-- <el-button
            type="primary"
            @click="innerDrawerVisible = true"
          >去支付</el-button> -->

        </div>
        <div>
          <span style="font-weight:bold">总计：¥{{ cartTotalPrice.toFixed(2) }}</span>
        </div>
        <el-button
          style="margin-top:10px"
          type="success"
          size="large"
          @click="submitOrder"
        >提交订单</el-button>
      </div>

      <el-drawer
        v-model="innerDrawerVisible"
        title="请支付"
        :append-to-body="true"
        size="80%"
        direction="btt"
        class="mobile-drawer"
        header-class="drawer-header"
      >
        <div style="display: flex;flex-direction:column;justify-content:center;align-items: center">

          <h1 style="color:red">请支付¥{{ cartTotalPrice.toFixed(2) }}</h1>
          <h1 style="color:red">支付时请备注工号姓名!!</h1>
          <div>
            <el-image
              style="width: 100%; height: 100%"
              :src="Qrcode_pay"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :preview-src-list="payDoneImgList"
              show-progress
              :initial-index="0"
              fit="cover"
            />
            <!-- <el-image
              style="width: 100px; height: 100px;"
              :src="payDoneImgWX"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :preview-src-list="payDoneImgList"
              show-progress
              :initial-index="1"
              fit="cover"
            />
            <el-image
              style="width: 100px; height: 100px;margin-left:10px"
              :src="payDoneImgZFB"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :preview-src-list="payDoneImgList"
              show-progress
              :initial-index="2"
              fit="cover"
            /> -->
          </div>
          <!-- <img
            width="100px"
            height="100px"
            src="@/assets/Qrcode_pay.png"
            alt=""
          > -->
          <!-- <h1 style="color:red">请支付¥{{ cartTotalPrice.toFixed(2) }} 并备注工号姓名!!</h1> -->
          <!-- <span>请支付¥{{ cartTotalPrice.toFixed(2) }}</span> -->

          <!-- <div style="padding:1px">
            <FileUploadVue @fileChanged="fileChanged"></FileUploadVue>
          </div> -->
          <el-button
            style="margin-top:10px"
            type="success"
            size="large"
            @click="submitOrder"
          >提交订单</el-button>

          <!-- <el-button
            style="margin-top:10px"
            type="primary"
            @click="innerDrawerVisible = false"
          >上传支付截图</el-button> -->
        </div>
      </el-drawer>
    </el-drawer>
  </div>
</template>

<script setup>
import Qrcode_pay from '@/assets/Qrcode_pay.png';
import WMTS from '@/assets/WMTS.png';

import FileUploadVue from '@/components/FileUpload.vue';
import { showSuccess, showWarning } from '@/hooks/useMyMessageBox';
import myAxios from '@/myAxios/myAxios';
import { ref, reactive, computed, onMounted, h } from 'vue';
import { v4 } from 'uuid';
import { dayjs } from 'element-plus';
import VueCookie from 'vue-cookie';
import { ForkSpoon, } from '@element-plus/icons-vue';
import myAxiosWXPost from '@/myAxios/myAxiosWXPost';
import router from '@/router';

// 菜单数据
const menu = reactive([
  // {
  //   CD_ID: 1,
  //   NAME: '宫保鸡丁',
  //   PRICE: 38,
  //   DESCRIPTION: '经典川菜，麻辣鲜香',
  //   URL: `http://htqdds.haitian.com:9911/qdmes/CHER/driver_order_menu/img/menu/`
  // },
]);

// 购物车数据
const cartItems = reactive([]);
const drawerVisible = ref(false);
const innerDrawerVisible = ref(false);
const showDescription = ref(window.innerWidth > 768);

// 购物车操作方法
const addToCart = (event, item) => {
  console.log('event :>> ', event);
  const existing = cartItems.find(i => i.CD_ID === item.CD_ID);
  if (existing) {
    existing.quantity++;
  } else {
    cartItems.push({ ...item, quantity: 1 });
  }

  // 购物车动画
  let targetShop = document.getElementById('pcShop');
  if (window.innerWidth < 768) {
    targetShop = document.getElementById('mobileShop');
  }
  createBall(event.target, targetShop);
  // createBall(document.getElementById('div1'), document.getElementById('div2'));
};

const increaseQuantity = (index) => {
  cartItems[index].quantity++;
};

const decreaseQuantity = (index) => {
  if (cartItems[index].quantity > 1) {
    cartItems[index].quantity--;
  } else {
    cartItems.splice(index, 1);
  }
};

const removeItem = (index) => {
  cartItems.splice(index, 1);
};

let payDoneImgWX = ref('http://htqdds.haitian.com:9911/qdmes/CHER/driver_order_menu/img/order/微信截图范例.jpeg');
let payDoneImgZFB = ref('http://htqdds.haitian.com:9911/qdmes/CHER/driver_order_menu/img/order/支付宝截图范例.jpeg');
let payDoneImgList = ref([
  Qrcode_pay,
  // 'http://htqdds.haitian.com:9911/qdmes/CHER/driver_order_menu/img/order/微信截图范例.jpeg',
  // 'http://htqdds.haitian.com:9911/qdmes/CHER/driver_order_menu/img/order/支付宝截图范例.jpeg'
]);

// 计算属性
const cartTotalPrice = computed(() =>
  cartItems.reduce((sum, item) => sum + item.PRICE * item.quantity, 0)
);

const cartTotalQuantity = computed(() =>
  cartItems.reduce((sum, item) => sum + item.quantity, 0)
);

// 响应式布局
window.addEventListener('resize', () => {
  showDescription.value = window.innerWidth > 768;
});

const YY_TIME = ref('');
const YY_TIME_Options = ref([
]);
// 预约时间选项,今天17点前下单明天取,17点后下单后天取
// for (let i = 1; i < 8; i++) {
//   let date = dayjs().add(i, 'day');
//   let day = date.day();
//   if (day == 0 || day == 6) {
//     continue;
//   }
//   else {
//     let isPush = false;
//     if (i == 1) {
//       let hour = date.hour();
//       // 17点前下单明天取
//       if (hour < 17) {
//         isPush = true;
//       }
//       else {
//         isPush = false;
//       }
//     }
//     else {
//       isPush = true;
//     }
//     if (isPush) {
//       let value = `${date.format('YYYY/MM/DD')} 15:30-16:30`;
//       YY_TIME_Options.value.push({
//         value: value,
//         label: value,
//       });
//     }
//   }
// }
const REMARK = ref('');

const fileChanged = (event) => {
  // console.log('event :>> ', event.target.files[0]);
  var reader = new FileReader();
  reader.onload = async (e) => {
    let filename = `${`test`}.jpeg`;
    let filePath = `D:\\QDMES\\CHER\\driver_order_menu\\img\\menu\\`;
    let result = await myAxios.uploadFile(e.target.result, filePath, filename);
    if (result.includes('成功')) {
      showSuccess("上传成功");
    }
    else {
      showWarning("上传失败" + result);
    }
  };
  reader.readAsDataURL(event.target.files[0]);
};

const WORKID = VueCookie.get('userid');
const NAME = VueCookie.get('username');
const submitOrder = async () => {
  let CD_RECORD_ID = v4();
  let STATE = '待确认';
  let CREATE_TIME = dayjs().format('YYYY/MM/DD HH:mm:ss');
  let DONE_TIME = ``;
  let PUSH_TIME = true ? CREATE_TIME : ``;
  let URL = ``;

  let params = `${CD_RECORD_ID}\t${STATE}\t${CREATE_TIME}\t${YY_TIME_Options.value[0].value}`
    + `\t${WORKID}\t${NAME}\t${DONE_TIME}\t${REMARK.value}`
    + `\t${cartTotalPrice.value}\t${PUSH_TIME}\t${URL}`;
  myAxios.post('陈帅廷添加或修改食堂点菜记录', params).then(async res => {
    if (res.includes('成功')) {
      for (let i = 0; i < cartItems.length; i++) {
        let CD_ITEM_ID = v4();
        let QTY = cartItems[i].quantity;

        // myAxios会自动去除null,导致json字符串有问题,设个空值保证JSON没问题
        cartItems[i].DESCRIPTION = cartItems[i].DESCRIPTION ? cartItems[i].DESCRIPTION : '';

        let CD_JSON = JSON.stringify(cartItems[i]);
        let itemParam = `${CD_ITEM_ID}\t${QTY}\t${CD_RECORD_ID}\t${CD_JSON}`;
        let result = await myAxios.post('陈帅廷添加或修改菜单记录', itemParam, '9900');
        if (!result.includes('成功')) {
          showWarning('提交菜单失败!' + result);
        }
        else {
        }
      }
      showSuccess('提交成功!' + res);
      let order = {
        WORKID: WORKID,
        CD_RECORD_ID: CD_RECORD_ID,
        USERNAME: NAME,
        RECORD_TIME: CREATE_TIME,
      };
      SendTemplate_WX(order);
      router.push({ path: '/history', query: { CD_RECORD_ID: CD_RECORD_ID } });
    }
    else {
      showWarning('更新失败res!' + res);
    }
  }).catch((err) => {
    showWarning('更新失败err!' + err);
  });

};


const SendTemplate_WX = (order, isSuccess = true) => {
  // let BX_NAME = bxName(order.BX_ID);
  let RECORD_TIME = order.RECORD_TIME;
  let NAME = order.USERNAME;
  let url = `http://smart.haitian.com/Cheresting/driver_order_menu/dist/index.html#/history`
    + `?CD_RECORD_ID=${order.CD_RECORD_ID}`;
  let content = {
    'openId': 'ok-KS08CgnvAOLKnALEL142tsqYk',
    'url': url,
    'title': `${'点心外卖预约'}` + isSuccess ? '' : ' 已取消',
    'data1': `${'点心外卖预约'}` + isSuccess ? '' : ' 已取消',
    'data2': `${RECORD_TIME}`,
    'data3': `${order.WORKID} ${NAME}`,
    // 'description': '外卖订单/包厢订单',
    // 'picurl': '11',
    'remark': '请及时接收',
    'tokenname': 'ACCESS_TOKEN_WX_QDFW'
  };
  myAxiosWXPost.post(`http://192.168.100.28:85/WorkWxMsgService/WxWorkMsgService.asmx`,
    `SendTemplate_WX`, content)
    .then(pushRes => {
      // if (pushRes.includes('成功')) {
      //   let nowStr = dayjs().format('YYYY/MM/DD HH:mm:ss');
      //   myAxios.post('陈帅廷更新食堂包厢记录推送时间', `${order.BX_RECORD_ID}\t${nowStr}`);
      // }
      // console.log('pushRes :>> ', pushRes);
    });
};

onMounted(() => {
  let cdParam = `${''}`;
  myAxios.get('陈帅廷查询食堂固定菜单', cdParam, '9900').then(async res => {
    menu.length = 0;
    res.forEach(el => {
      el.ORIURL = el.URL;
      el.URL = `http://htqdds.haitian.com:9911/qdmes/CHER/driver_order_menu/img/menu/` + el.ORIURL;
    });
    menu.push(...res);


    // 预约时间选项,周四16点前下单周五取,16点后下单下周五取

    //开始日期默认为下一个周五
    let date = dayjs();
    let startFriday = date.day(5);
    // 如果是周六会取到昨天,所以判断一下
    if (startFriday.isBefore(date)) {
      startFriday = startFriday.add(7, 'day');
    }
    let nowStr = date.format('YYYY/MM/DD');
    let fridayStr = startFriday.format('YYYY/MM/DD');
    // 周四16点后下单 后一个周五取
    if (date.day() == 4) {
      let hour = date.hour();
      if (hour >= 16) {
        startFriday = startFriday.add(7, 'day');
      }
    }

    // 获取后面四个周五,总不至于连续四个周五都放假
    for (let i = 0; i < 4; i++) {
      fridayStr = startFriday.add(i * 7, 'day').format('YYYY/MM/DD');
      let content = {
        'date': fridayStr,
      };
      let dateInfo = await myAxiosWXPost.post(`http://192.168.100.28:39911/CHLWebService.asmx`, `CheckDateType`, content);
      console.log('dateInfo :>> ', dateInfo);
      // 日期类型 0：工作日 1:假日(周末) 2：节假日
      if (dateInfo.type == 0) {
        YY_TIME_Options.value.push({
          value: `${fridayStr} 15:30-16:30`,
          label: `${fridayStr} 15:30-16:30`,
        });
        break;
      }
    }
  });


  ElMessageBox({
    title: '温馨提示',
    confirmButtonClass: 'selfConfirmButtonClass',
    message: h('p', null, [
      h('img', { src: WMTS, style: { width: '100%' } },)
      // h('h3', { style: { textAlign: 'center' } }, '预约说明'),
      // h('ol', { style: { paddingLeft: '20px', fontSize: '14px' } }, [
      //   h('li', null, '营业时间: 每周工作日和周六中餐'),
      //   h('li', null, '开餐时间: 中午11:50-13:00,晚上17:30-20:00'),
      //   h('li', null, '餐厅入口: 驱动食堂东北门'),
      //   h('li', null, '关于酒水: 食堂提供饮料和啤酒(费用另结算)其他酒水,须自行携带'),
      //   h('li', null, '预约时间: 至少提前一天,17:00截止,当天不受理'),
      // ]),
      // h('div', { style: { paddingLeft: '20px' } }, '联系方式：屈经理（651018,13566511216）'),
    ]),
    callback: () => {
    },
  });
});

let ball = ref(null);
// let ballStyle = ref(
//   {

//   }
//   );
//播放动画
let createBall = function (startElement, endElement) {
  // 设置初始位置（按钮中心）
  const btn = startElement;
  const btnRect = btn.getBoundingClientRect();
  const startX = btnRect.left + btnRect.width / 2 - 10;
  const startY = btnRect.top + btnRect.height / 2 - 10 + window.scrollY;
  console.log('startX :>> ', startX);
  console.log('startY :>> ', startY);
  // 设置终点位置
  const endElementRect = endElement.getBoundingClientRect();
  const endX = endElementRect.left + endElementRect.width / 2;
  const endY = endElementRect.top + endElementRect.height / 2 + window.scrollY;
  console.log('endX :>> ', endX);
  console.log('endY :>> ', endY);

  // 初始化小球位置
  ball.value.style.left = startX + 'px';
  ball.value.style.top = startY + 'px';
  // document.body.appendChild(ball);

  // 动画参数配置
  const amplitude = 0;  // 抛物线高度（负值=向上弯曲）
  const duration = 500;   // 动画持续时间（毫秒）
  const startTime = Date.now();
  ball.value.style.display = 'block';

  // 动画循环
  function animate () {
    const currentTime = Date.now();
    const elapsed = currentTime - startTime;
    const progress = Math.min(elapsed / duration, 1);
    // console.log(' :>> ',);
    // 抛物线运动计算
    const currentX = startX + progress * (endX - startX);
    const currentY = startY + progress * (endY - startY)
      + amplitude * progress * (1 - progress);

    // 更新位置
    ball.value.style.left = currentX + 'px';
    ball.value.style.top = currentY + 'px';

    // 动画结束处理
    if (progress < 1) {
      requestAnimationFrame(animate);
    } else {
      // ball.value.style.opacity = '0';
      setTimeout(() => {
        ball.value.style.display = 'none';
      }, 0);
    }
  }

  requestAnimationFrame(animate);
}
</script>


<style>
.el-message-box__title {
  font-size: 13px;
}
.selfConfirmButtonClass {
  background-color: white !important;
  border-color: #dcdfe6;
  color: rgb(0, 53, 140);
}
.selfConfirmButtonClass:hover {
  background-color: white !important;
  border-color: #dcdfe6;
  color: rgb(0, 53, 140);
}
.selfConfirmButtonClass:focus-visible {
  background-color: white !important;
  border-color: #dcdfe6;
  color: rgb(0, 53, 140);
}
.ball {
  position: absolute;
  width: 20px;
  height: 20px;
  background-color: var(--el-color-primary);
  border-radius: 50%;
  transition: opacity 0.3s;
  z-index: 9999;
  display: none;
}

.container {
  padding: 10px;
  max-width: 1200px;
  margin: 0 auto;
}

.menu-item {
  margin-bottom: 10px;
}

.item-image {
  width: 100%;
  height: 150px;
  object-fit: cover;
  border-radius: 4px;
}

.item-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
}

.PRICE {
  color: #e6a23c;
  font-weight: bold;
  font-size: 18px;
}

.cart-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #ebeef5;
}

.quantity-control {
  display: flex;
  align-items: center;
  gap: 8px;
}

.quantity {
  min-width: 24px;
  text-align: center;
}

.mobile-cart {
  display: none;
  position: fixed;
  right: 20px;
  bottom: 20px;
  z-index: 2000;
}

.total-PRICE {
  text-align: right;
  padding: 0px 0;
}

@media (max-width: 768px) {
  .mobile-cart {
    display: block;
  }

  .DESCRIPTION {
    display: none;
  }

  .cart-desktop {
    display: none;
  }
}

/* .mobile-drawer {
  padding: 20px;
} */
.drawer-header {
  padding: 0px;
  margin-bottom: 0px;
}
</style>